package com.quyeying.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * ossUtil
 * @author shenkaixin
 */
@Slf4j
@Component
public class OssUtil {

    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.secretKey}")
    private String secretKey;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.url}")
    private String url;

    //自定义上传域名，华东z0，华北z1，华南z2
    public static Region regionHD() {
        return (new Region.Builder()).
                srcUpHost("upload-z2.qiniup.com").
                accUpHost("upload-z2.qiniup.com").
                iovipHost("iovip-z2.qbox.me").
                rsHost("rs-z2.qbox.me").
                rsfHost("rsf-z2.qbox.me").
                apiHost("api-z2.qiniu.com").build();
    }

    public String upload(InputStream inputStream, String name) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(OssUtil.regionHD());

        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = name;
        StringMap policy = new StringMap();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, null, 3600, policy);

        long start = System.currentTimeMillis();
        try {
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("上传耗时-----毫秒：{}",System.currentTimeMillis()-start);
            //这个是上传到七牛云服务器的路径定义
            return url + key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.info(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return "error";
    }

    /**
     * 抓取网络资源到空间
     * @param remoteSrcUrl
     * @return
     */
    public String fetch(String remoteSrcUrl){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        //抓取网络资源到空间
        try {
            FetchRet fetchRet = bucketManager.fetch(remoteSrcUrl, bucket);
            log.info("转换后的url"+url+fetchRet.key);
            return url + fetchRet.key;
        } catch (QiniuException ex) {
            log.error(ex.response.toString());
        }
        return null;
    }

    public boolean removeFile(String fileName) {

        Configuration cfg = new Configuration(Region.autoRegion());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            Response response = bucketManager.delete(bucket, fileName.replaceAll(url, ""));
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return false;
    }

    /**
     * 客户端上传需要的token
     * @return
     */
    public Map<String,String> getToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Map<String,String> map = new HashMap<>();
        map.put("upToken",upToken);
        map.put("url",url);
        return map;
    }

    /**
     * 客户端上传需要的覆盖token
     * @return
     */
    public Object getCoverToken(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, key);
        return upToken;
    }

    /**
     * 获取七牛配置信息
     * @return
     */
    public String getUploadData() {
        return url;
    }
}
